package com.atguigu.crowd.service.impl;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.AdminExample;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUseException;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUseForUpdateException;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.mapper.AdminMapper;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.util.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * information
 * Created by Administrator on 2020/3/18.
 */
@Service
public class AdminServiceImpl implements AdminService{

    private Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public void saveAdmin(Admin admin) {
        //密码加密
        String userPswd = admin.getUserPswd();
        String encodePassword = bCryptPasswordEncoder.encode(userPswd);
        //userPswd = CrowdUtil.md5(userPswd);
        admin.setUserPswd(encodePassword);

        //生成创建实际
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creatDate = format.format(date);
        admin.setCreateTime(creatDate);

        // 3.执行保存
        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
            e.printStackTrace();

            logger.info("异常全类名="+e.getClass().getName());

            if(e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }

    }

    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {

        //1.根据登录账号查询Admin对象
        //①创建AdminExample对象
        AdminExample adminExample = new AdminExample();
        //②创建Criteria对象
        AdminExample.Criteria criteria = adminExample.createCriteria();
        //③在Criteria对象中封装查询条件
        criteria.andLoginAcctEqualTo(loginAcct);
        //④调用AdminMapper的方法执行查询
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        //2.判断Admin对象是否为null
        if (adminList==null || adminList.size()==0){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILD);
        }
        if (adminList.size()>1){
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }
        Admin admin = adminList.get(0);

        //3.如果Admin对象为null为空则抛出异常
        if(admin==null){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILD);
        }

        //4.如果Admin对象不为null则将数据库密码从对象中取出
        String userPswdDB = admin.getUserPswd();

        //5.将表单提交的密码进行加密
        String userPswdForm = CrowdUtil.md5(userPswd);

        //6.对密码进行比较
        if (!Objects.equals(userPswdDB,userPswdForm)){
            //7.如果比较结果是不一致则抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILD);
        }

        //8.如果一致则返回Admin对象
        return admin;
    }

    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
        //1.调用PageHelper的静态方法开启分页功能
        //这里充分体现了PageHelper的非侵入式设计，原本要做的查询不必有任何修改
        PageHelper.startPage(pageNum,pageSize);

        //2.执行查询
        List<Admin> admins = adminMapper.selectAdminByKeyword(keyword);

        //封装到PageInfo对象中
        return new PageInfo<>(admins);
    }

    @Override
    public void remove(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public Admin getAdminByAdminId(Integer adminId) {

        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void update(Admin admin) {
        //"selective"表示有选择的更新，对应null值的不更新
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            e.printStackTrace();

            logger.info("异常全类名="+e.getClass().getName());

            if(e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseForUpdateException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }

    }

    @Override
    public void removeAdmin(List<String> adminAcctList) {

        AdminExample adminExample = new AdminExample();

        AdminExample.Criteria criteria = adminExample.createCriteria();

        //delete from t_admin where id in (5,8,12)
        criteria.andLoginAcctIn(adminAcctList);

        adminMapper.deleteByExample(adminExample);

    }

    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {

        //先根据adminId删除旧数据，在保存全部的旧数据
        adminMapper.deleteOldRelationship(adminId);

        //保存新的数据
        if (roleIdList != null && roleIdList.size()>0){

        adminMapper.insertNewRelationship(adminId,roleIdList);
        }

    }

    @Override
    public Admin getAdminByLoginAcct(String username) {

        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(username);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        Admin admin = adminList.get(0);


        return admin;
    }
}
